package com.dataStructure.Thread;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CyclicBarrier;

/**
 * 赛马问题，所有马都准备好，才开始跑
 * 所有马都跑完，才开始宣布成绩
 */
public class HorseTracing {
    static List<String> list = new CopyOnWriteArrayList<>();

    static CyclicBarrier horseReady = new CyclicBarrier(10);

    static CyclicBarrier horseEnd = new CyclicBarrier(10, new Runnable() {
        @Override
        public void run() {
            System.out.println("裁判宣布成绩....");
        }
    });


    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            new Thread(new Horse("马" + i)).start();
        }

        Thread.sleep(2000);
    }


    static class Horse implements Runnable {
        String name;
        @Override
        public void run() {
            try {
                System.out.println(name + " 准备好了");
                horseReady.await();
                System.out.println(name + "开跑了");
                //模拟马跑的时间
                int time = new Random().nextInt(10);
                Thread.sleep(1000 * time);
                System.out.println(name + time + "s到达终点");
                list.add(time + name + "s到达终点");
                horseEnd.await();

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public Horse(String name) {
            this.name = name;
        }
    }
}


